package com.learning.springmvc.advance.view.view;

import com.learning.springmvc.advance.view.bean.User;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.servlet.view.document.AbstractXlsxView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * ClassName: ExcelView
 * Description: Excel 视图
 * Date: 2020/2/1 16:48 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class ExcelView extends AbstractXlsxView {

    @Override
    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook,
                                      HttpServletRequest request, HttpServletResponse response) throws Exception {

//        response.setHeader("Content-Disposition", "inline;filename=" + new String("用户列表".getBytes(), "iso8859-1"));
        response.setHeader("Content-Disposition", "attachment;filename=" + new String("用户列表".getBytes(), "iso8859-1"));
        User user = (User) model.get("user");

        Sheet sheet = workbook.createSheet("user");
        Row header = sheet.createRow(0);

        header.createCell(0).setCellValue("姓名");
        header.createCell(1).setCellValue("电话");
        header.createCell(2).setCellValue("生日");

        Row row = sheet.createRow(1);
        row.createCell(0).setCellValue(user.getName());
        row.createCell(1).setCellValue(user.getMobile());

        Date birthday = user.getBirthday();
        if (Objects.nonNull(birthday)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
            row.createCell(2).setCellValue(format.format(birthday));
        }
    }
}
